import Vue from 'vue'
import Router from 'vue-router'
import { constantRoutes } from './router.config.js'

import store from '@/store'

import scorllBehavior from './scrollBehavior.js'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

const createRouter = () =>
  new Router({
    // mode: 'history',  // 如果你是 history模式 需要配置vue.config.js publicPath
    // base: process.env.BASE_URL,
    scrollBehavior: scorllBehavior,
    routes: constantRoutes
  })

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

router.beforeEach((to, form, next) => {
  console.log('to:', to, 'form:', form)
  const role = localStorage.getItem('role')
  console.log('----------role:', role)
  if ((localStorage.getItem('token') && role) || to.path === '/login') {
    // 获取角色
    console.log('stroe.state:', store.state.permission.routes)
    if (store.state.permission.routes.length <= 0) {
      resetRouter()
      store.dispatch('permission/getRoute', role).then(routes => {
        console.log('router模块中，routes:', routes)
        router.addRoutes(routes)
      })
    }
    if (to.name) {
      store.dispatch('layout/addTabs', to)
    }

    next()
  } else {
    next('/login')
  }
})

export default router
